//
//  Uliti.swift
//  物料商行
//
//  Created by HaoDong Hong on 2017/9/3.
//  Copyright © 2017年 HaoDong Hong. All rights reserved.
//

import UIKit
import SwiftMessages

extension UIViewController {
    func showSuccess(message: String) {
        let view = MessageView.viewFromNib(layout: .CardView)
        view.configureTheme(.warning)
        view.button?.isHidden = true
        view.configureDropShadow()
        view.configureContent(title: "成功", body: message, iconText: "😀")
        SwiftMessages.show(view: view)
    }
    
    func showError(message: String) {
        let view = MessageView.viewFromNib(layout: .CardView)
        view.configureTheme(.warning)
        view.button?.isHidden = true
        view.configureDropShadow()
        view.configureTheme(backgroundColor: .red, foregroundColor: .white)
        view.configureContent(title: "错误", body: message, iconText: "🙄")
        SwiftMessages.show(view: view)
    }
    
    func convertToBase64(_ image: UIImage) -> String? {
        if let png = UIImageJPEGRepresentation(image, 0.05) {
            return "data:image/png;base64,\(png.base64EncodedString())"
        } else if let jpeg = UIImagePNGRepresentation(image) {
            return "data:image/png;base64,\(jpeg.base64EncodedString())"
        }
        return nil
    }
    func generateQRCode(from string: String, scale: CGFloat = 3) -> UIImage? {
        let data = string.data(using: String.Encoding.ascii)
        
        if let filter = CIFilter(name: "CIQRCodeGenerator") {
            filter.setValue(data, forKey: "inputMessage")
            let transform = CGAffineTransform(scaleX: scale, y: scale)
            
            if let output = filter.outputImage?.transformed(by: transform) {
                return UIImage(ciImage: output)
            }
        }
        return nil
    }
}

extension UIAlertController {
    func addAlert(_ title: String, action: @escaping (UIAlertAction) -> Void ) {
        let alert = UIAlertAction(title: title, style: .default, handler: action)
        addAction(alert)
    }

}

extension UITableViewCell {
    func convertToBase64(_ image: UIImage) -> String? {
        if let png = UIImageJPEGRepresentation(image, 0.05) {
            return "data:image/png;base64,\(png.base64EncodedString())"
        } else if let jpeg = UIImagePNGRepresentation(image) {
            return "data:image/png;base64,\(jpeg.base64EncodedString())"
        }
        return nil
    }
}

extension Optional where Wrapped == String {
    var nilIfEmpty: String? {
        guard let strongSelf = self else {
            return nil
        }
        return strongSelf.isEmpty ? nil : strongSelf
    }
}

class AlertController: UIAlertController {
    /// - Return: value that was set on `title`
    private(set) var originalTitle: String?
    private var spaceAdjustedTitle: String = ""
    private weak var imageView: UIImageView? = nil
    private var previousImgViewSize: CGSize = .zero
    
    override var title: String? {
        didSet {
            // Keep track of original title
            if title != spaceAdjustedTitle {
                originalTitle = title
            }
        }
    }
    
    /// - parameter image: `UIImage` to be displayed about title label
    func setTitleImage(_ image: UIImage?) {
        guard let imageView = self.imageView else {
            let imageView = UIImageView(image: image)
            self.view.addSubview(imageView)
            self.imageView = imageView
            return
        }
        imageView.image = image
    }
    
    // MARK: -  Layout code
    
    override func viewDidLayoutSubviews() {
        guard let imageView = imageView else {
            super.viewDidLayoutSubviews()
            return
        }
        // Adjust title if image size has changed
        if previousImgViewSize != imageView.bounds.size {
            previousImgViewSize = imageView.bounds.size
            adjustTitle(for: imageView)
        }
        // Position `imageView`
        let linesCount = newLinesCount(for: imageView)
        let padding = Constants.padding(for: preferredStyle)
        imageView.center.x = view.bounds.width / 2.0
        imageView.center.y = padding + linesCount * lineHeight / 2.0
        super.viewDidLayoutSubviews()
    }
    
    /// Adds appropriate number of "\n" to `title` text to make space for `imageView`
    private func adjustTitle(for imageView: UIImageView) {
        let linesCount = Int(newLinesCount(for: imageView))
        let lines = (0..<linesCount).map({ _ in "\n" }).reduce("", +)
        spaceAdjustedTitle = lines + (originalTitle ?? "")
        title = spaceAdjustedTitle
    }
    
    /// - Return: Number new line chars needed to make enough space for `imageView`
    private func newLinesCount(for imageView: UIImageView) -> CGFloat {
        return ceil(imageView.bounds.height / lineHeight)
    }
    
    /// Calculated based on system font line height
    private lazy var lineHeight: CGFloat = {
        let style: UIFontTextStyle = self.preferredStyle == .alert ? .headline : .callout
        return UIFont.preferredFont(forTextStyle: style).pointSize
    }()
    
    struct Constants {
        static var paddingAlert: CGFloat = 22
        static var paddingSheet: CGFloat = 11
        static func padding(for style: UIAlertControllerStyle) -> CGFloat {
            return style == .alert ? Constants.paddingAlert : Constants.paddingSheet
        }
    }
}

